package Client;

import java.net.*;
import java.io.*;

/**
 * The CentralServer class is used to facilitate
 * all the communication with a Galaxia
 * Central CentralServer.
 * @author Jithesh, Nevil, Saurav, Sajin ,Vineeth
 */
public class CentralServer {
	/**
	 * The CentralServer(String ipAddress) constructor
	 * is used to supply the host name of the 
	 * central server to connect to.
	 * @param ipAddress Host Name/ IPAddress of a Galaxia CentralServer.
	 */
	public CentralServer(String ipAddress) throws UnknownHostException {
		serverAddress = InetAddress.getByName(ipAddress);
	}

	/**
	 * The getPublicKey function is
	 * used to retrieve the public
	 * key of the server to which the
	 * (@link CentralServer) object is connected to.
	 * @return A (@link String) containing the public key.
	 */
	public String getPublicKey() {
		String reply = null;
		try {
			Socket server = new Socket(serverAddress, serverPort);
			DataInputStream fromServer = new DataInputStream( server.getInputStream() );
			DataOutputStream toServer = new DataOutputStream( server.getOutputStream() );

			/* The message format for getting the public key is.
			 *  Type ( 4 bits )    : 0000
			 *  PadBits ( 4 bits ) : 0000
			 */
			
			byte[] requestMsg = new byte[1];
			byte[] replyMsg = new byte[1024]; // The key can be atmost 1KB.
			
			requestMsg[0] = 0;
			toServer.write(requestMsg);
			fromServer.read(replyMsg);
			reply = new String(replyMsg);
		} catch ( IOException iexp ) {
			System.err.println("Error occured " + iexp.getMessage() );
		}

		return reply;
	}

	public String[] findNodes(String key) {
		return null;
	}

	public static final int serverPort = 6000;
	protected InetAddress serverAddress;
}
